#include <iostream>
#include <fstream>
#include <string>
#include <string.h>
#include <algorithm>  
#include <fstream>

using namespace std;

const char *HEAD_GUIDE = "@@NameBig@@";
const char *CLASS_NAME = "@@Name@@";

bool replace(string &input, const char *src, const char *dest)
{
	int pos = input.find(src);
    while (pos > 0) {

       	input.replace(pos, strlen(src), dest);
    	pos = input.find(src, pos);
    	// cout << pos << endl;
    	// cout << dest << endl; 
    }
}

bool createHeaderFile(const char *filePath, const char *name) 
{
	ifstream file (filePath);
    string value;

    string output = "";
    int i = 0;

    bool isTest = (strstr(filePath, "test") != NULL);
    string strName = "";
    if (isTest) {
    	strName.append("Test");
    }
    strName.append(name);

    string str = strName;
    transform(str.begin(), str.end(), str.begin(), ::toupper);

    while ( file.good() )
    {

        getline (file, value, '\r');

        replace(value, HEAD_GUIDE, str.c_str());
        replace(value, CLASS_NAME, strName.c_str());

        output.append(value); 
    }
    // cout << output << endl;

    std::string filename = "out/";
    filename.append(strName.c_str());
    filename.append(".h");
   	ofstream fout(filename.c_str());
	fout << output << endl;
}

bool createClassFile(const char *filePath, const  char *name)
{
	ifstream file (filePath);
    string value;

    bool isTest = (strstr(filePath, "test") != NULL);
    string str = "";
    if (isTest) {
    	str.append("Test");
    }
    str.append(name);

    string output = "";
    int i = 0;
    while ( file.good() )
    {
        getline (file, value, '\r');

        replace(value, CLASS_NAME, str.c_str());

        output.append(value); 
    }
    
    std::string filename = "out/";
    filename.append(str.c_str());
    filename.append(".cpp");
   	ofstream fout(filename.c_str());
	fout << output << endl;
}

int main(int argc, char *argv[]) 
{
    for (int i = 0; i < argc; i++)
        printf("Argument %d is %s.\n", i, argv[i]);

    cout << "argc = " << argc << endl;

    system("mkdir out");
	if (argc == 2) {
		createClassFile("template/classTemp", argv[1]);
		createHeaderFile("template/headerTemp", argv[1]);
		createClassFile("template/testClassTemp", argv[1]);
		createHeaderFile("template/testHeadTemp", argv[1]);
	}
	else {

	}

    return 0;
}

